package com.peko.demo.utils;

import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map.Entry;

import java.util.*;

/**
 * 封装 HttpClient 工具类
 */
public class HttpUtils {
    /**
     * 连接池
     */
    private static PoolingHttpClientConnectionManager cm;

    /**
     * 用于Get方法的参数
     */
    public static Map<String,String> headerMap = null;

    /**
     * 请求配置
     */
    private static RequestConfig config = null;

    static {
        cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(200);
        cm.setDefaultMaxPerRoute(20);


        config = RequestConfig.custom()
                .setSocketTimeout(10000) //设置连接超时时间
                .setConnectTimeout(10000) //设置创建连接超时时间
                .setConnectionRequestTimeout(10000) //设置请求超时时间
                .build();

        headerMap = new HashMap<>();
    }

    /**
     * get 方法
     * 请求参数放在url上
     * @param url
     * @return
     */
    public static String doGet(String url){
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(config).build();
        HttpGet httpGet = new HttpGet(url);
        //放进所有请求头
        Set<Entry<String, String>> entrySet = headerMap.entrySet();
        for (Entry<String, String> o : entrySet) {
            httpGet.setHeader(o.getKey(),o.getValue());
        }

        CloseableHttpResponse response = null;
        String ret = null;
        try{
            response = httpClient.execute(httpGet);

            if(response.getStatusLine().getStatusCode() == 200){
                if(response.getEntity() != null){
                    ret = EntityUtils.toString(response.getEntity(), "UTF-8");
//                    System.out.println(html);
                }
            }

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }

        return ret;
    }

    /**
     * get 方法
     * @param url
     * @param params 请求参数
     * @return
     * @throws URISyntaxException
     */
    public static String doGet(String url,List<NameValuePair> params){
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(config).build();

        URI newUrl = null;
        try {
            newUrl = new URIBuilder(url).setParameters(params).build();
        }catch (URISyntaxException e){
            e.printStackTrace();
        }

        HttpGet httpGet = new HttpGet(newUrl);
        //放进所有请求头
        Set<Entry<String, String>> entrySet = headerMap.entrySet();
        for (Entry<String, String> o : entrySet) {
            httpGet.setHeader(o.getKey(),o.getValue());
        }

        CloseableHttpResponse response = null;
        String ret = null;
        try{
            response = httpClient.execute(httpGet);

            if(response.getStatusLine().getStatusCode() == 200){
                if(response.getEntity() != null){
                    ret = EntityUtils.toString(response.getEntity(), "UTF-8");
//                    System.out.println(html);
                }
            }

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }

        return ret;
    }

    /**
     * post 方法
     * @param url
     * @param params 请求参数
     * @return
     */
    public static String doPost(String url,List<NameValuePair> params) throws IOException {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(config).build();

        HttpPost httpPost = new HttpPost(url);
        //准备参数
        params.add(new BasicNameValuePair("username","xx"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
        httpPost.setEntity(entity);

        //放进所有请求头
        Set<Entry<String, String>> entrySet = headerMap.entrySet();
        for (Entry<String, String> o : entrySet) {
            httpPost.setHeader(o.getKey(),o.getValue());
        }

        //3、发起请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        String ret = null;
        //4、获取响应数据
        if(response.getStatusLine().getStatusCode() == 200){
            ret = EntityUtils.toString(response.getEntity(), "UTF-8");
//            System.out.println(ret);
        }
        //5、关闭资源
        httpClient.close();

        return ret;
    }

    public static void main(String[] args) {
        HttpUtils.doGet("http://www.itcast.cn/?username=xx");
    }
}
